<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';

import { ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { Button } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

// Props
const props = defineProps<{
  field: any;
}>();

// Emits
const emit = defineEmits<{
  cancel: [];
  update: [field: any];
}>();

// 响应式数据
const saving = ref(false);

// 生成表单Schema
const generateFormSchema = (): VbenFormSchema[] => {
  const baseSchema = [
    {
      fieldName: 'name',
      label: '字段名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入字段名称',
      },
      rules: 'required',
    },
    {
      fieldName: 'label',
      label: '显示标签',
      component: 'Input',
      componentProps: {
        placeholder: '请输入显示标签',
      },
      rules: 'required',
    },
    {
      fieldName: 'type',
      label: '字段类型',
      component: 'Select',
      componentProps: {
        placeholder: '请选择字段类型',
        options: [
          { label: '文本', value: 'STRING' },
          { label: '数字', value: 'NUMBER' },
          { label: '布尔', value: 'BOOLEAN' },
          { label: '日期', value: 'DATE' },
          { label: '选择', value: 'SELECT' },
          { label: '多行文本', value: 'TEXTAREA' },
          { label: '文件上传', value: 'UPLOAD' },
        ],
      },
      rules: 'required',
    },
    {
      fieldName: 'required',
      label: '是否必填',
      component: 'Switch',
    },
    {
      fieldName: 'defaultValue',
      label: '默认值',
      component: 'Input',
      componentProps: {
        placeholder: '请输入默认值',
      },
    },
    {
      fieldName: 'placeholder',
      label: '占位符',
      component: 'Input',
      componentProps: {
        placeholder: '请输入占位符',
      },
    },
  ];

  // 如果是Select类型，添加选项配置
  if (props.field?.type === 'SELECT') {
    baseSchema.push({
      fieldName: 'options',
      label: '选项配置',
      component: 'InputTextArea',
      componentProps: {
        placeholder:
          '请输入选项配置，格式：[{"label": "选项1", "value": "value1"}]',
      },
    });
  }

  return baseSchema;
};

// 使用useVbenForm
const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  schema: generateFormSchema(),
  showDefaultActions: false,
});

// 保存字段
const saveField = async () => {
  saving.value = true;
  try {
    const { valid } = await formApi.validate();
    if (!valid) return;

    const formData = await formApi.getValues();

    // 处理选项数据
    let options = [];
    if (formData.type === 'SELECT' && formData.options) {
      try {
        options = JSON.parse(formData.options);
      } catch (error) {
        console.error('解析选项数据失败:', error);
        options = [];
      }
    }

    const updatedField = {
      ...props.field,
      ...formData,
      options,
      uiConfig: {
        ...props.field.uiConfig,
        placeholder: formData.placeholder,
        placeholderplaceholder,
      },
    };

    emit('update', updatedField);
  } catch (error) {
    console.error('保存字段失败:', error);
  } finally {
    saving.value = false;
  }
};

// 初始化表单数据
const initFormData = async () => {
  if (props.field) {
    const formData = {
      name: props.field.name,
      label: props.field.label,
      type: props.field.type,
      required: props.field.required,
      defaultValue: props.field.defaultValue,
      placeholder: props.field.uiConfig?.placeholder,
    };
    await formApi.setValues(formData);
  }
};

// 组件挂载时初始化数据
initFormData();
</script>

<template>
  <div class="field-editor-v2">
    <div class="editor-header">
      <h3>字段配置</h3>
      <div class="header-actions">
        <Button type="primary" @click="saveField" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存
        </Button>
        <Button @click="$emit('cancel')">
          <IconifyIcon icon="ant-design:close-outlined" />
          取消
        </Button>
      </div>
    </div>

    <div class="editor-content">
      <Form />
    </div>
  </div>
</template>

<style lang="less" scoped>
.field-editor-v2 {
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .editor-content {
    padding: 16px 0;
  }
}
</style>
